    // 全局变量
    let currentFilter = 'all';
    let currentTypeFilter = 'all';
    let wrongQuestions = [];
    let currentPracticeSession = {
    questions: [],
    currentIndex: 0,
    score: 0,
    isWrongQuestionMode: false
};

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
    loadWrongQuestions();
});

    // 加载错题数据
    async function loadWrongQuestions() {
    try {
    const userId = getUserId();
    if (!userId) {
    throw new Error('用户未登录');
}

    const response = await fetch(`/api/wrong-questions/user/${userId}`);

    if (!response.ok) {
    throw new Error('获取错题失败');
}

    wrongQuestions = await response.json();
    renderWrongQuestions();

} catch (error) {
    console.error('加载错题出错:', error);
    showError('加载错题失败，请稍后重试');
}
}

    // 渲染错题列表
    function renderWrongQuestions() {
    const container = document.getElementById('wrong-questions-list');

    if (!wrongQuestions || wrongQuestions.length === 0) {
    container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">📚</div>
                    <h3>暂无错题记录</h3>
                    <p>开始练习后，错题会自动记录在这里</p>
                </div>
            `;
    return;
}

    // 根据当前筛选条件过滤错题
    const filteredQuestions = wrongQuestions.filter(q => {
    const categoryMatch = currentFilter === 'all' || q.category === currentFilter;
    const typeMatch = currentTypeFilter === 'all' || q.type === currentTypeFilter;
    return categoryMatch && typeMatch;
});

    if (filteredQuestions.length === 0) {
    container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">🔍</div>
                    <h3>没有找到符合条件的错题</h3>
                    <p>尝试更改筛选条件</p>
                </div>
            `;
    return;
}

    // 渲染错题列表
    container.innerHTML = filteredQuestions.map(q => `
            <div class="wrong-question-item" data-id="${q.id}">
                <div class="question-header">
                    <div class="question-title">
                        ${getQuestionTypeName(q.type)}
                        <span class="wrong-count">错误 ${q.wrongCount} 次</span>
                    </div>
                    <div class="question-meta">
                        <span>${getExamName(q.category)}</span>
                    </div>
                </div>

                <div class="question-content">
                    ${formatQuestionContent(q)}
                </div>

                <div class="answer-section">
                    <div class="user-answer">
                        <strong>你的答案:</strong> ${formatUserAnswer(q)}
                    </div>
                    <div class="correct-answer">
                        <strong>正确答案:</strong> ${formatCorrectAnswer(q)}
                    </div>
                </div>

                <div class="analysis">
                    <strong>解析:</strong>
                    <div class="analysis-content">${q.analysis || '暂无解析'}</div>
                </div>

                <div class="notes-section">
                    <strong>我的笔记:</strong>
                    <textarea class="notes-textarea" placeholder="可以在这里添加自己的笔记...">${q.notes || ''}</textarea>
                </div>

                <div class="question-actions">
                    <button class="action-btn save-notes-btn" onclick="saveNotes('${q.id}')">保存笔记</button>
                    <button class="action-btn practice-again-btn" onclick="practiceAgain('${q.id}')">再练一次</button>
                </div>
            </div>
        `).join('');
}

    // 保存笔记
    async function saveNotes(questionId) {
    const notes = document.querySelector(`.wrong-question-item[data-id="${questionId}"] .notes-textarea`).value;

    try {
    const response = await fetch(`/api/wrong-questions/${questionId}/notes`, {
    method: 'PUT',
    headers: {
    'Content-Type': 'application/json'
},
    body: JSON.stringify({
    notes: notes
})
});

    if (!response.ok) {
    throw new Error('保存笔记失败');
}

    // 更新本地数据
    const question = wrongQuestions.find(q => q.id === questionId);
    if (question) {
    question.notes = notes;
}

    showSuccess('笔记保存成功');

} catch (error) {
    console.error('保存笔记出错:', error);
    showError('保存笔记失败，请稍后重试');
}
}

    // 再练一次
    async function practiceAgain(questionId) {
    try {
    const response = await fetch(`/api/wrong-questions/${questionId}`);

    if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
}

    // 检查响应是否有内容
    const text = await response.text();
    if (!text) {
    throw new Error('服务器返回空响应');
}

    const question = JSON.parse(text);

    if (!question) {
    showError('未找到该题目');
    return;
}

    // 修正字段映射
    const practiceQuestion = {
    id: question.id,
    type: question.type,
    category: question.category,
    content: question.questionContent || question.content, // 兼容两种字段名
    answer: question.correctAnswer || question.answer,    // 兼容两种字段名
    analysis: question.analysis,
    userAnswer: question.userAnswer
};

    // 设置练习会话为单题模式
    currentPracticeSession = {
    questions: [practiceQuestion],
    currentIndex: 0,
    score: 0,
    isWrongQuestionMode: true // 标记为错题练习模式
};

    // 显示练习页面
    document.querySelector('.question-container').style.display = 'none';
    document.getElementById('practice-screen').style.display = 'block';

    // 更新标题
    document.getElementById('current-practice-title').textContent = '错题重练';

    // 显示题目
    showCurrentQuestion();

} catch (error) {
    console.error('获取错题详情失败:', error);
    showError(`获取题目失败: ${error.message}`);
}
}

    // 检查答案
    async function checkAnswer() {
    const userId = getUserId();
    if (!userId) {
    showError('用户未登录，请重新登录');
    return;
}

    const question = currentPracticeSession.questions[currentPracticeSession.currentIndex];
    if (!question) {
    showError('当前题目无效');
    return;
}

    const userAnswer = getUserAnswer(question.type);
    if (!userAnswer && question.type !== 'writing' && question.type !== 'translation') {
    showError('请选择一个答案');
    return;
}

    try {
    const isCorrect = evaluateAnswer(question, userAnswer);

    // 如果回答错误，记录错题
    if (!isCorrect) {
    await recordWrongQuestion(question, userAnswer, userId);
}

    // 显示结果
    showAnswerResult(question, userAnswer, isCorrect);

    // 更新分数和索引
    if (isCorrect) currentPracticeSession.score++;
    updateButtonState();

} catch (error) {
    console.error('提交答案出错:', error);
    showError('提交答案失败: ' + error.message);
}
}

    // 记录错题
    async function recordWrongQuestion(question, userAnswer, userId) {
    try {
    // 1. 检查是否已经是错题
    const checkResponse = await fetch(`/api/wrong-questions/user/${userId}/question/${question.id}`);

    if (!checkResponse.ok && checkResponse.status !== 404) {
    throw new Error('检查错题记录失败');
}

    // 2. 如果已有记录，则更新
    if (checkResponse.ok) {
    const existingQuestion = await checkResponse.json();

    const updatedQuestion = {
    ...existingQuestion,
    wrongCount: existingQuestion.wrongCount + 1, // 增加错题次数
    userAnswer: userAnswer // 更新用户答案
};

    const updateResponse = await fetch(`/api/wrong-questions/${existingQuestion.id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(updatedQuestion)
});

    if (!updateResponse.ok) {
    throw new Error('更新错题失败');
}

    return await updateResponse.json();
}

} catch (error) {
    console.error('记录错题出错:', error);
    throw error;
}
}
    // 显示当前题目
    function showCurrentQuestion() {
    const { questions, currentIndex } = currentPracticeSession;
    const question = questions[currentIndex];
    const container = document.getElementById('practice-content');
    const submitBtn = document.querySelector('.submit-btn');

    submitBtn.textContent = '提交答案';
    submitBtn.onclick = checkAnswer;

    container.innerHTML = `
            <div class="practice-question" data-id="${question.id}">
                <div class="progress">${currentIndex + 1}/${questions.length}</div>
                <h3>${getQuestionTypeName(question.type)}</h3>
                <div class="question-content">${formatPracticeContent(question)}</div>
                ${renderAnswerArea(question)}
            </div>
        `;
}

    // 获取用户答案
    function getUserAnswer(questionType) {
    if (questionType === 'reading') {
    let userAnswer = "";
    for (let i = 1; i <= 5; i++) {
    const selected = document.querySelector(`input[name="q${i}"]:checked`);
    userAnswer += selected ? selected.value : "_"; // 用_表示未选
}
    return userAnswer;
}
    return document.querySelector('.answer-area')?.value;
}

    // 显示答案结果
    function showAnswerResult(question, userAnswer, isCorrect) {
    let resultHTML = '';

    if (question.type === 'reading') {
    resultHTML = `
                <div class="result ${isCorrect ? 'correct' : 'incorrect'}">
                    <h3>${isCorrect ? '✓ 全部正确' : '✗ 有错误'}</h3>
                    <div class="answers-comparison">
                        <p>您的答案: ${userAnswer}</p>
                        <p>正确答案: ${question.answer}</p>
                        <div class="analysis">
                            <strong>解析:</strong>
                            <div class="analysis-content">${question.analysis || '暂无解析'}</div>
                        </div>
                    </div>
                </div>
            `;
} else {
    // 其他题型保持原有显示方式
    resultHTML = `
                <div class="result ${isCorrect ? 'correct' : 'incorrect'}">
                    <h3>${isCorrect ? '✓ 正确' : '✗ 错误'}</h3>
                    <div class="correct-answer">
                        <strong>正确答案:</strong>
                        <div>${question.answer}</div>
                    </div>
                    <div class="analysis">
                        <strong>解析:</strong>
                        <div class="analysis-content">${question.analysis || '暂无解析'}</div>
                    </div>
                </div>
            `;
}

    document.getElementById('practice-content').insertAdjacentHTML('beforeend', resultHTML);
}

    // 更新按钮状态
    function updateButtonState() {
    const submitBtn = document.querySelector('.submit-btn');
    if (!submitBtn) return;

    // 确保按钮始终可见
    submitBtn.style.display = 'block';

    if (currentPracticeSession.currentIndex < currentPracticeSession.questions.length - 1) {
    submitBtn.textContent = '下一题';
    submitBtn.onclick = function() {
    currentPracticeSession.currentIndex++;
    showCurrentQuestion();
};
} else {
    submitBtn.textContent = '完成练习';
    submitBtn.onclick = showPracticeResult;
}
}

    // 显示练习结果
    function showPracticeResult() {
    const { score, questions, isWrongQuestionMode } = currentPracticeSession;
    const percentage = Math.round((score / questions.length) * 100);

    let resultHTML = `
            <div class="practice-result">
                <h2>${isWrongQuestionMode ? '错题练习完成' : '练习完成!'}</h2>
                <div class="score">得分: ${score}/${questions.length} (${percentage}%)</div>
        `;

    const submitBtn = document.querySelector('.submit-btn');
    if (isWrongQuestionMode) {
    resultHTML += `<button class="back-btn" onclick="backToWrongQuestions()">返回错题列表</button>`;
    if (submitBtn) {
    submitBtn.style.display = 'none';
}
} else {
    resultHTML += `</div>`;
    if (submitBtn) {
    submitBtn.style.display = 'block';
    submitBtn.textContent = '返回首页';
    submitBtn.onclick = resetPractice;
}
}

    document.getElementById('practice-content').innerHTML = resultHTML;
}

    // 返回错题列表
    function backToWrongQuestions() {
    document.getElementById('practice-screen').style.display = 'none';
    document.querySelector('.question-container').style.display = 'block';
    loadWrongQuestions();
}

    // 重置练习
    function resetPractice() {
    currentPracticeSession = {
        questions: [],
        currentIndex: 0,
        score: 0,
        isWrongQuestionMode: false
    };

    document.getElementById('practice-screen').style.display = 'none';
    document.querySelector('.question-container').style.display = 'block';
}

    // 筛选错题
    function filterWrongQuestions(filter) {
    currentFilter = filter;

    // 更新导航激活状态
    document.querySelectorAll('.nav-category').forEach(item => {
    item.classList.remove('active');
});
    event.currentTarget.classList.add('active');

    renderWrongQuestions();
}

    // 按类型筛选
    function filterByType(type) {
    currentTypeFilter = type;

    // 更新按钮状态
    document.querySelectorAll('.type-btn').forEach(btn => {
    btn.classList.remove('active');
});
    event.currentTarget.classList.add('active');

    renderWrongQuestions();
}

    function getQuestionTypeName(type) {
    const typeMap = {
    reading: '阅读理解',
    writing: '写作',
    translation: '翻译'
};
    return typeMap[type] || type;
}

    function getExamName(examType) {
    const examMap = {
    CET4: '大学英语四级',
    CET6: '大学英语六级',
    PE: '考研英语'
};
    return examMap[examType] || examType;
}

    function formatQuestionContent(question) {
    switch(question.type) {
    case 'reading':
    return `<div class="passage">${question.questionContent}</div>`;
    case 'writing':
    return `<div class="prompt">${question.questionContent}</div>`;
    case 'translation':
    return `<div class="source-text">${question.questionContent}</div>`;
    default:
    return `<div>${question.questionContent}</div>`;
}
}

    function formatUserAnswer(question) {
    if (question.type === 'reading') {
    return question.userAnswer.split('').join(' ');
}
    return question.userAnswer || '无';
}

    function formatCorrectAnswer(question) {
    if (question.type === 'reading') {
    return question.correctAnswer.split('').join(' ');
}
    return question.correctAnswer;
}

    function renderAnswerArea(question) {
    switch(question.type) {
    case 'reading':
    let html = '<div class="options-container">';
    for (let i = 1; i <= 5; i++) {
    html += `
                        <div class="question-row">
                            <div class="question-number">第${i}题</div>
                            <div class="options-row">
                                ${['A', 'B', 'C', 'D'].map(opt => `
                                    <label class="option">
                                        <input type="radio" name="q${i}" value="${opt}">
                                        <span class="option-letter">${opt}</span>
                                    </label>
                                `).join('')}
                            </div>
                        </div>
                    `;
}
    html += '</div>';
    return html;
    case 'writing':
    return `<textarea class="answer-area" placeholder="请输入你的作文..."></textarea>`;
    case 'translation':
    return `<textarea class="answer-area" placeholder="请输入你的翻译..."></textarea>`;
    default:
    return `<input type="text" class="answer-area" placeholder="请输入你的答案...">`;
}
}

    function evaluateAnswer(question, userAnswer) {
    if (question.type === 'reading') {
    // 对于阅读题，比较每个答案
    return userAnswer === question.answer;
} else {
    // 对于其他题型，简单比较（实际可能需要更复杂的比较逻辑）
    return userAnswer.trim().toLowerCase() === question.answer.trim().toLowerCase();
}
}

    function showError(message) {
    alert('错误: ' + message);
}

    function showSuccess(message) {
    alert('成功: ' + message);
}

    function getUserId() {
    const userIdEl = document.getElementById('userId');
    if (!userIdEl || !userIdEl.value) {
    console.error('无法获取用户ID');
    showError('用户未登录，请重新登录');
    return null;
}
    return parseInt(userIdEl.value);
}

    window.filterWrongQuestions = filterWrongQuestions;
    window.filterByType = filterByType;
    window.saveNotes = saveNotes;
    window.practiceAgain = practiceAgain;
    window.backToWrongQuestions = backToWrongQuestions;